<template>
  <el-container class="tag-manager">
    <el-aside width="250px">
      <div class="tool-bar-wrapper">
        <el-icon><Menu /></el-icon>
        <span class="title">数据库</span>
        <div class="button">
          <el-tooltip class="box-item" effect="dark" content="创建数据库" placement="top">
            <el-button size="small" @click="openCreateDatabaseDialog">
              <el-icon>
                <Plus />
              </el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
      <el-menu style="height: calc(100% - 39px)" @select="handleSelect" @close="handleClose">
        <div v-for="(item, index) in store.databaseInfo" :key="index">
          <el-sub-menu popper-class="pcolor" :index="item">
            <template #title>
              <el-icon>
                <span class="iconfont icon-OP_Dateshuju"></span>
              </el-icon>
              <span> {{ item }}</span>
            </template>
            <el-menu-item :index="item + '.stable'">
              <span>stable</span>
            </el-menu-item>
            <el-menu-item :index="item + '.table'">
              <span>table</span>
            </el-menu-item>
          </el-sub-menu>
        </div>
      </el-menu>
    </el-aside>
    <el-main class="main">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="`已选择数据库：${currentDb}`" name="tableInfo">
          <!--超表列表详情-->
          <div class="super-table-info-wrapper" v-show="tableType === 'stable'">
            <div class="tool-bar-wrapper">
              <el-form :inline="true">
                <el-form-item label="超表名">
                  <el-input size="small" placeholder="请输入表名" v-model.trim="searchWord" clearable />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="getTableByPageAndName('')" class="el-icon-search" size="small"
                    >查询</el-button
                  >
                  <el-button type="default" @click="createTableDialogOpen(1)" class="el-icon-plus" size="small"
                    >创建超表</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
            <el-table
              style="height: calc(100% - 83px); width: 100%"
              :data="stData"
              stripe
              border
              v-loading="stableLoading"
            >
              <template #empty>
                <el-empty />
              </template>
              <el-table-column prop="table_name" label="名称" width="300" align="center">
                <template #default="scope">
                  <el-tag type="primary">{{ scope.row.table_name }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="operations" label="操作" align="center">
                <template #default="scope">
                  <el-button size="small" @click="btn_showTables(scope.row)"> 查看子表 </el-button>
                  <el-button size="small" @click="() => createTableDialogOpen(3, scope.row)"> 创建子表 </el-button>
                  <el-button size="small" @click="clickAlterTableButton(scope.row)"> 编辑 </el-button>
                  <el-button size="small" type="danger" @click="clickDeleteButton(scope.row)"> 删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              style="margin-top: 12px; float: right"
              v-model:current-page="pageInfo.PAGE_NO"
              v-model:page-size="pageInfo.PAGE_SIZE"
              :page-sizes="[10, 20, 50, 100]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageInfo.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
          <!-- 子表详情 -->
          <div v-show="tableType === 'table'" style="height: 100%">
            <table-dialog
              @createTableDialogOpen="createTableDialogOpen"
              :dbName="currentDb"
              :dialogWidth="dialogWidth"
              :height="height - 150"
              :tableType="tableType"
              @editChildTable="editChildTableEmit"
              :dbInfo="props.dbInfo"
              :databaseInfo="props.databaseInfo"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <!--从超表跳转子表的dialog-->
    <el-dialog title="子表" v-model="dialogVisible" width="80%" style="height: 70%">
      <table-dialog
        :dbName="currentDb"
        :stable="currentStable"
        :dialogWidth="dialogWidth"
        :visiable="dialogVisible"
        :dbInfo="props.dbInfo"
        :databaseInfo="props.databaseInfo"
      />
    </el-dialog>
    <!-- 创建超表或者子表 -->
    <el-dialog
      class="dialog-wrapper"
      :title="createTableDialogTitle"
      v-model="createTableDialogVisiable"
      width="50%"
      style="height: 500px"
    >
      <div style="height: 428px" v-loading="createTableLoading">
        <create-table
          ref="createTableRef"
          :type="createTableType"
          :visiable="createTableDialogVisiable"
          :superTableInfo="superTableInfo"
        ></create-table>
        <div style="position: absolute; bottom: 10px; right: 24px">
          <el-button type="primary" @click="createTableButton">确定</el-button>
          <el-button @click="createTableDialogVisiable = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 修改表结构 -->
    <el-dialog
      class="dialog-wrapper"
      :title="alterTableDialogTitle"
      v-model="alterTableDialogVisiable"
      width="50%"
      top="50px"
      style="max-height: 550px"
    >
      <AlterTable
        :tableName="alterTableName"
        :tableType="alterTableType"
        :visiable="alterTableDialogVisiable"
        :dbName="currentDb"
        :dbInfo="props.dbInfo"
        :databaseInfo="props.databaseInfo"
      >
      </AlterTable>
    </el-dialog>
    <el-dialog title="创建数据库" v-model="createDatabaseDialogVisiable" width="500px" style="height: 150px">
      <div style="height: 100%" v-loading="createDatabaseLoading">
        <el-form ref="createDbsRef" label-width="auto" :model="createDatabaseForm">
          <el-form-item
            prop="databaseName"
            label="数据库名称"
            :rules="[
              {
                required: true,
                message: '请输入数据库名称',
                trigger: 'blur',
              },
              {
                validator: checkDatabaseName,
                trigger: 'blur',
              },
            ]"
          >
            <el-input v-model="createDatabaseForm.databaseName" maxlength="32" />
          </el-form-item>
        </el-form>
        <div style="position: absolute; bottom: 10px; right: 12px">
          <el-button type="primary" @click="clickConfirmCreateDatabase">确定</el-button>
          <el-button @click="createDatabaseDialogVisiable = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </el-container>
</template>

<script lang="tsx" setup>
import { ref, watch, computed, defineProps, defineEmits } from 'vue';
import { onMounted } from "vue";
import { ElMessage, ElButton, ElIcon, ElTag, ElMessageBox } from "element-plus";
import {
  addCustomSuperTable,
  addCustomTable,
  getTableStructure,
  addChildTable,
  getTableByPage,
  deleteTable,
  createDatabase,
} from "@/api/index";

import TableDialog from "./TableDialog.vue";
import CreateTable from "./CreateTable.vue";
import AlterTable from "./AlterTable.vue";

//属性值
const props = defineProps({
  dbInfo: {
    type: Object,
    default: {},
  },
  databaseInfo: {
    type: Array,
    default: [],
  },
});

//table还是stable
const tableType = ref("");
const dialogVisible = ref(false);

const height = ref();
const dialogWidth = ref(0);
const store = {
  info: props.dbInfo,
  databaseInfo: props.databaseInfo,
};
const currentDb = ref("");
const currentStable = ref("");

//超表搜索条件
const searchWord = ref("");
//超表数据
const stData = ref([]);
//创建表格数据
const createTableRef = ref(null);
const createTableInfo = ref(null);
const createTableDialogTitle = ref("");
//1 超级表 2 普通表 3 子表
const createTableType = ref(1);
//控制创建表弹窗显示隐藏
const createTableDialogVisiable = ref(false);
//创建子表时需要用到的超级表信息
const superTableInfo = ref(null);
const createTableLoading = ref(false);
//打开创建表弹窗
const createTableDialogOpen = (type: Number, superTable: any) => {
  createTableType.value = type;
  createTableDialogVisiable.value = true;
  if (type == 1) {
    createTableDialogTitle.value = "创建超表";
  } else if (type == 2) {
    createTableDialogTitle.value = "创建普通表";
  } else {
    createTableDialogTitle.value = "创建子表";
    //获取表的结构
    createTableLoading.value = true;
    let params = {
      dbConfig: {
        ...store.info,
        dbName: currentDb.value,
      },
      tableDto: {
        name: superTable.table_name,
        columnsInfo: [],
        tagsInfo: [],
      },
    };
    getTableStructure(params).then((res: any) => {
      if (res.code == 200 && res.data) {
        superTableInfo.value = res.data;
        createTableLoading.value = false;
      } else {
        ElMessage({
          message: "获取超级表字段信息失败",
          type: "error",
        });
        createTableLoading.value = false;
        createTableDialogVisiable.value = false;
      }
    });
  }
};
/**
 * 点击创建表按钮
 */
const createTableButton = () => {
  if (!createTableRef || !createTableRef.value || !createTableRef.value.tableInfo) {
    return;
  }
  createTableRef.value.formRef.validate((res: boolean) => {
    if (res) {
      createTableInfo.value = createTableRef.value.tableInfo;
      let params = {
        dbConfig: {
          ...store.info,
          dbName: currentDb.value,
        },
        tableDto: null,
      };
      if (createTableType.value == 1) {
        params.tableDto = JSON.parse(JSON.stringify(createTableInfo.value));
        addCustomSuperTable(params)
          .then((res: any) => {
            if (res.code == 200 && res.data) {
              ElMessage({
                message: "创建超级表成功",
                type: "success",
              });
              getTableByPageAndName("");
            } else {
              ElMessage({
                message: "创建超级表失败：" + res.msg,
                type: "error",
              });
            }
            createTableDialogVisiable.value = false;
          })
          .catch(() => {
            createTableDialogVisiable.value = false;
          });
      } else if (createTableType.value == 2) {
        params.tableDto = JSON.parse(JSON.stringify(createTableInfo.value));
        addCustomTable(params)
          .then((res: any) => {
            if (res.code == 200 && res.data) {
              ElMessage({
                message: "创建普通表成功",
                type: "success",
              });
              getTableByPageAndName("");
            } else {
              ElMessage({
                message: "创建普通表失败：" + res.msg,
                type: "error",
              });
            }
            createTableDialogVisiable.value = false;
          })
          .catch(() => {
            createTableDialogVisiable.value = false;
          });
      } else {
        params.tableDto = {};
        params.tableDto.tagsInfo = JSON.parse(JSON.stringify(createTableRef.value.childTableTags));
        //超级表名称
        params.tableDto.name = createTableInfo.value.name;
        params.tableDto.supName = superTableInfo.value.name;
        addChildTable(params)
          .then((res: any) => {
            if (res.code == 200 && res.data) {
              ElMessage({
                message: "创建子表成功",
                type: "success",
              });
              getTableByPageAndName("");
            } else {
              ElMessage({
                message: "创建子表失败：" + res.msg,
                type: "error",
              });
            }
            createTableDialogVisiable.value = false;
          })
          .catch(() => {
            createTableDialogVisiable.value = false;
          });
      }
    }
  });
};

//tab页
const activeName = ref("tableInfo");
//menu菜单打开回调
const handleOpen = (key: string) => {
  currentDb.value = key;
};
//分页配置
const pageInfo = ref({
  PAGE_NO: 1,
  PAGE_SIZE: 20,
  total: 100,
});
const stableLoading = ref(false);
/**
 * 当前页修改
 * @param val 当前页
 */
const handleCurrentChange = (val: number) => {
  pageInfo.value.PAGE_NO = val;
  getTableByPageAndName("");
};
/**
 * 每页数据量修改
 * @param val 每页数据量
 */
const handleSizeChange = (val: number) => {
  pageInfo.value.PAGE_SIZE = val;
  getTableByPageAndName("");
};

/**
 * 分页获取表格
 * @param superTableName 超表名称用于查询指定子表
 */
const getTableByPageAndName = (superTableName: string) => {
  stableLoading.value = true;
  let data = {
    filterName: searchWord.value,
    dbConfig: {
      ...store.info,
      dbName: currentDb.value,
    },
    isSuperTable: tableType.value == "stable" ? true : false,
    superTableName,
    page: {
      ...pageInfo.value,
    },
  };
  getTableByPage(JSON.parse(JSON.stringify(data)))
    .then((res: object) => {
      if (res.code == 200 && res.data && res.data.list) {
        if (tableType.value == "stable") {
          //超级表赋值
          stData.value = res.data.list.map((item: string) => {
            return {
              table_name: item.name,
              table_type: "SUPER_TABLE",
            };
          });
        }
        pageInfo.value.total = res.data.total;
      } else {
        stData.value = [];
        ElMessage({
          message: "创建表格数据失败",
          type: "error",
        });
      }
      stableLoading.value = false;
    })
    .catch(() => {
      stableLoading.value = false;
    });
};

/**
 * 选择表格，初始化表格信息
 * @param key
 * @param keyPath
 */
const handleSelect = (key: string, keyPath: string[]) => {
  currentDb.value = keyPath[0];
  //判断是stable还是table
  if (key.indexOf(".stable") > 0) {
    tableType.value = "stable";
    getTableByPageAndName("");
  } else if (key.indexOf(".table") > 0) {
    tableType.value = "table";
  }
};

const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

/**
 * 从超表跳转到子表列表
 * @param cellData
 */
const btn_showTables = (cellData: any) => {
  dialogVisible.value = true;
  let name = cellData.table_name;
  currentStable.value = name;
};

onMounted(() => {
  setTimeout(() => {
    init();
  }, 100);
});

watch(
  (deep: any) => store.info,
  (val) => {
    if (val && store.connected) {
      init();
    }
  }
);

const init = () => {
  height.value = document.documentElement.clientHeight - 30;
  dialogWidth.value = document.documentElement.clientWidth * 0.8 - 10;
};

const clickDeleteButton = (rowData) => {
  // 删除表的逻辑
  ElMessageBox.confirm("删除超级表会自动删除通过超级表创建的子表以及子表中的所有数据", "删除表格", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = {
        dbConfig: {
          ...store.info,
          dbName: currentDb.value,
        },
        tableName: rowData.table_name,
      };
      deleteTable(data)
        .then((res) => {
          if (res.code == 200 && res.data) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
            getTableByPageAndName("");
          } else {
            ElMessage({
              type: "error",
              message: "删除失败：" + res.msg,
            });
          }
        })
        .catch(() => {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const searchConidtionST = () => {
  let keyword = searchWord.value;
};

const searchConidtion = () => {
  let keyword = searchWord.value;
};

const handleClick = (tab: any) => {
  console.log(tab);
};

// const columns = generateColumns(10)
// const data = generateData(columns, 100000)

/**
 * 修改表部分的代码
 */
//弹窗显隐
const alterTableDialogVisiable = ref(false);
//修改表类型 true 超表 false 普通表
const alterTableType = ref(true);
//修改表名
const alterTableName = ref("");
//弹窗标题
const alterTableDialogTitle = computed(() => {
  return alterTableType ? "修改超级表" : "修改普通表";
});
const clickAlterTableButton = (rowData) => {
  alterTableType.value = tableType.value == "stable" ? true : false;
  alterTableName.value = rowData.table_name;
  alterTableDialogVisiable.value = true;
};
const editChildTableEmit = (tableName) => {
  alterTableType.value = false;
  alterTableName.value = tableName;
  alterTableDialogVisiable.value = true;
};

/**
 * 创建数据库相关内容
 */
const createDbsRef = ref(null);
const createDatabaseDialogVisiable = ref(false);
const createDatabaseForm = ref({
  databaseName: "",
});
const createDatabaseLoading = ref(false);
const openCreateDatabaseDialog = () => {
  createDatabaseDialogVisiable.value = true;
  createDatabaseForm.value.databaseName = "";
	if(createDbsRef.value){
		createDbsRef.value.clearValidate();
	}
};
const emits = defineEmits(['createDatabase']);
const clickConfirmCreateDatabase = () => {
  if (createDbsRef.value) {
    createDbsRef.value.validate((res) => {
      if (res) {
        createDatabaseLoading.value = true;
        let data = {
          ...store.info,
          dbName: createDatabaseForm.value.databaseName,
        };
        createDatabase(data)
          .then((res) => {
            if (res.code == 200 && res.data) {
              ElMessage({
                type: "success",
                message: "创建成功",
              });
              let payload = store.info;
              if (!payload.host) {
                return;
              }
							emits('createDatabase')
              createDatabaseDialogVisiable.value = false;
            } else {
              ElMessage({
                type: "error",
                message: "创建失败：" + res.msg,
              });
            }
            createDatabaseLoading.value = false;
          })
          .catch((error) => {
            console.log(error);
            ElMessage({
              type: "error",
              message: "创建失败",
            });
            createDatabaseLoading.value = false;
          });
      }
    });
  }
};

const checkDatabaseName = (rule, value, callback) => {
  if (/^[A-Za-z][A-Za-z0-9_]*$/.test(value)) {
    callback();
  } else {
    callback(new Error("数据库名称需要字母开头，只能包括字母、数字、下划线。"));
  }
};
</script>

<style lang="less" scoped>
.tag-manager {
  .main {
    padding: 12px;

    .super-table-info-wrapper {
      height: 100%;
      overflow: auto;
    }
  }

  .tool-bar-wrapper {
    height: 38px;
    position: relative;
    padding-left: 20px;
    border-bottom: 1px solid #dcdfe6;
    border-right: 1px solid #dcdfe6;
    .title {
      line-height: 38px;
      display: inline-block;
      margin-left: 12px;
    }
    .button {
      position: absolute;
      right: 6px;
      top: 0;
      height: 100%;
      width: 40px;
      display: flex;
      align-items: center;
      flex-direction: row-reverse;
    }
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      height: calc(100% - 40px);
    }
  }
}

.el-sub-menu.is-active {
  background-color: #a2d2ff;
}

/* 覆盖菜单激活项的背景颜色 */
.el-menu-item.is-active {
  color: hsl(246, 100%, 54%) !important;
  /* 选中项的文本颜色 */
}

.pcolor {
  background-color: #051422;
}

.right {
  padding-left: 20px;
  line-height: 30px;
  float: right;
}

.codemirror {
  width: 100%;
  height: 300px;
}

.monaco-editor {
  width: 100%;
  height: 100%;
}
</style>
